<?php

namespace App\Http\Controllers\Admin;

use App\Models\ContestActivity;
use App\Models\ContestActivityWorks;
use App\Validate\ContestActivityValidate;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛活动
 * Class ContestType
 * @package app\admin\controller
 */
class ContestActivityController extends CommonController
{
    public $model = null;
    public $validate = null;
    public $worksModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ContestActivity();
        $this->validate = new ContestActivityValidate();
        $this->worksModel = new ContestActivityWorks();
    }


    /**
     * 获取报名参数
     */
    public function getContestActivityApplyParam()
    {
        $data = $this->model->getContestActivityApplyParam();
        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param node int 举办方式   1 独立活动  2 多馆联合   
     * @param is_play int 是否发布 1.发布 2.未发布    默认1
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 比赛开始时间(开始)
     * @param end_time datetime 比赛开始时间(截止)
     * @param create_start_time datetime 活动创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 活动创建结束时间
     */
    public function lists()
    {
        $page = request()->page ? intval(request()->page) : 1;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $node = request()->node;
        $is_play = request()->is_play;
        $keywords = request()->keywords;
        $start_time = request()->start_time;
        $end_time = request()->end_time;
        $create_start_time = request()->create_start_time;
        $create_end_time = request()->create_end_time;

        $res = $this->model->lists($node, $keywords, $start_time, $end_time, $create_start_time, $create_end_time, $is_play, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            $res['data'][$key]['unlook_num'] = $this->worksModel->getUnLookNumber($val['id']);
            $res['data'][$key]['uncheck_num'] = $this->worksModel->getUnCheckNumber($val['id']);
        }

        $res = $this->disPageData($res);
        //   $res['data'] = $this->addSerialNumber($res['data']);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 比赛id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->select(
            'id',
            'node',
            'title',
            'app_img as img',
            'host_handle',
            'tel',
            'con_start_time',
            'con_end_time',
            'vote_start_time',
            'vote_end_time',
            'is_reader',
            'vote_way',
            'number',
            'originals',
            'real_info',
            'intro',
            'rule_content',
            'is_play',
            'create_time'
        )->find($this->request->id);

        if (empty($res)) {
            return $this->returnApi(202, '参数传递错误');
        }

        $real_info_array = $this->model->getContestActivityApplyParam();
        // if ($res->real_info) {
        //     $real_info = explode("|", $res->real_info);
        //     $real_info_field = [];
        //     foreach ($real_info as $key => $val) {
        //         $temp = isset($real_info_array[$val - 1]) ? $real_info_array[$val - 1]['field'] : '';
        //         $real_info_field[] = $temp;
        //     }
        //     $res->real_info_field = $real_info_field;
        // } else {
        //     $res->real_info_field = null;
        // }

        $res->real_info_value = $this->getRealInfoArray($res->real_info, $real_info_array, 'value');
        $res->real_info_value = join("|", $res->real_info_value);

        $res->word_num = $this->worksModel->where('con_id', $this->request->id)->where('status', 1)->count();
        // $user_num = $this->worksModel->where('con_id', $this->request->id)->groupBy('user_id')->get(); //人次
        // $res->user_num = count($user_num); //人次

        $res->user_num = $this->worksModel->getTakeNumber($this->request->id); //人次

        $res->all_vote_num = $this->worksModel->where('con_id', $this->request->id)->sum('vote_num'); //总投票量
        $res->all_browse_num = $this->worksModel->where('con_id', $this->request->id)->sum('browse_num'); //总浏览量
        $res->all_word_num = $this->worksModel->where('con_id', $this->request->id)->whereIn('status', [1, 2, 3])->count();
        $res->approval_word_num = $this->worksModel->where('con_id', $this->request->id)->whereIn('status', [1, 2])->count();
        $res->unapproval_word_num = $this->worksModel->where('con_id', $this->request->id)->where('status', '=', 3)->count();

        //判断是否可以更改是否需要绑定读者证，有人预约就不允许修改
        $apply_status = $this->worksModel->actIsApply($this->request->id);
        $res['is_can_is_reader'] = $apply_status ? false : true; //false 有人报名，不允许修改

        //  $res['lib_name'] = $this->getLibNameByLibId($res['lib_id']);

        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param title string 名称
     * @param node string 举办方式   1 独立活动  2 多馆联合   
     * @param img string 活动封面
     * @param host_handle string 主办单位
     * @param con_start_time datetime 投稿开始时间
     * @param con_end_time datetime 投稿结束时间
     * @param vote_start_time datetime 投票开始时间
     * @param vote_end_time datetime 投票结束时间
     * @param tel string 电话号码 (咨询电话) 
     * @param vote_way int 投票方式   1  总票数方式   2 每次投票方式  3 无需投票
     * @param is_reader int 报名是否需要绑定读者证   1.是   2.否(默认）
     * @param number int 票数
     * @param originals text 原创申明 总配置  在每个馆也可单独设置  
    //  * @param promise text 作者承诺
     * @param intro text 简介
     * @param rule_content text 活动规则|活动内容
     * 
     * @param real_info text 需要验证的真实信息id用|连接起来    1、姓名   2 、身份证号码  3、电话号码   4、读者证号码    5、微信号 6、单位名称 7、指导老师  8、指导老师联系方式
     */
    public function add()
    {
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        if ($this->request->number > 100) {
            return $this->returnApi(201, "投票量不能超过100");
        }
        if ($this->request->vote_way != 3 && empty($this->request->number)) {
            return $this->returnApi(201, "请填写投票数");
        }
        if ($this->request->vote_way != 3 && (empty($this->request->vote_start_time) || empty($this->request->vote_end_time))) {
            return $this->returnApi(201, "投票时间不能为空");
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title');

        if ($is_exists) {
            return $this->returnApi(202, "该标题已存在");
        }

        DB::beginTransaction();
        try {
            $data = $this->request->all();
            $data['number'] = $this->request->vote_way == 3 ? 0 : $this->request->number;
            $data['app_img'] = $this->request->img;
            $data['manage_id'] = $this->request->manage_id;
            unset($data['img']);

            $this->model->add($data);

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "新增失败");
        }
    }

    /**
     * 编辑
     * @param id int 图书馆id
    // * @param node int 举办方式   1 独立活动  2 多馆联合   
     * @param title string 名称
     * @param img string 活动封面
     * @param host_handle string 主办单位
     * @param con_start_time datetime 投稿开始时间
     * @param con_end_time datetime 投稿结束时间
     * @param vote_start_time datetime 投票开始时间
     * @param vote_end_time datetime 投票结束时间
     * @param tel string 电话号码 (咨询电话)
     * @param vote_way int 投票方式   1  总票数方式   2 每次投票方式   3 无需投票
     * @param is_reader int 报名是否需要绑定读者证   1.是   2.否(默认）
     * @param number int 票数
     * @param originals text 原创申明 总配置  在每个馆也可单独设置    在单位哪里设置
    //  * @param promise text 作者承诺
     * @param intro text 简介
     * @param rule_content text 活动规则|活动内容
     * 
     * @param real_info text 需要验证的真实信息id用|连接起来    1、姓名   2 、身份证号码  3、电话号码   4、读者证号码    5、微信号 6、单位名称 7、指导老师  8、指导老师联系方式
     */
    public function change()
    {
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        if ($this->request->number > 100) {
            return $this->returnApi(201, "投票量不能超过100");
        }
        if ($this->request->vote_way != 3 && empty($this->request->number)) {
            return $this->returnApi(201, "请填写投票数");
        }
        if ($this->request->vote_way != 3 && (empty($this->request->vote_start_time) || empty($this->request->vote_end_time))) {
            return $this->returnApi(201, "投票时间不能为空");
        }
        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id);

        if ($is_exists) {
            return $this->returnApi(202, "该标题已存在");
        }

        $res = $this->model->where('is_del', 1)->find($this->request->id);

        if (!$res) {
            $this->returnApi(201, "参数传递错误");
        }

        if ($res->is_play == 1) {
            return $this->returnApi(201, "请先撤销，在进行修改！");
        }

        $old_img = $res->app_img;

        if ($this->request->node && $res->node != $this->request->node) {
            return $this->returnApi(201, "举办方式不能修改");
        }

        //已有用户参加，不允许修改
        if ($res->is_reader !=  $this->request->is_reader) {
            //判断是否有人报名
            $apply_status = $this->worksModel->actIsApply($this->request->id);
            if ($apply_status) {
                return $this->returnApi(201, "已有用户参加，不能修改是否需要绑定读者证参数");
            }
        }

        if ($this->request->vote != $res->vote || $this->request->vote_way != $res->vote_way) {
            //判断是否有人报名
            $vote_num = $this->worksModel->actIsVote($this->request->id);

            if ($vote_num) {
                return $this->returnApi(201, "已有用户投票，不能修改票数和投票方式");
            }
        }

        DB::beginTransaction();
        try {
            $data = $this->request->all();
            $data['number'] = $this->request->vote_way == 3 ? 0 : $this->request->number;
            $data['app_img'] = $this->request->img;
            unset($data['img']);

            $this->model->change($data);

            if ($old_img != $this->request->img) {
                $this->deleteFile($old_img);
            }

            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 比赛id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $apply_status = $this->worksModel->actIsApply($this->request->id);
        if ($apply_status) {
            return $this->returnApi(201, "已有用户参加，不能删除此活动");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }




    /**
     * 发布与取消发布
     * @param ids 书籍id，多个用逗号拼接   all 是，其余字符  ids 必传
     * @param is_play 是否发布  1.发布  2.未发布  默认2
     */
    public function playAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('play_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        list($code, $msg) = $this->model->resumeAndCancel($this->request->ids, 'is_play', $this->request->is_play);

        $is_play = $this->request->is_play == 1 ? '发布' : '取消发布';
        if ($code === 200) {
            return $this->returnApi(200, $is_play . $msg, true);
        }
        return $this->returnApi($code, $is_play . $msg);
    }
}
